﻿using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DataModel
{
    class MongoCRUD<T> where T : class
    {
        private MongoCollection<T> _collection;

        public MongoCRUD(MongoCollection<T> collection)
        {
            _collection = collection;
        }

        public bool Add(T elem)
        {
            var result = _collection.Insert<T>(elem);
            return (result.Ok && !result.HasLastErrorMessage);
        }

        public IList<T> Find(Expression<Func<T, bool>> filter = null)
        {
            return filter != null
                ? _collection.FindAs<T>(Query<T>.Where(filter)).ToList()
                : _collection.FindAll().ToList();
        }

        public bool Update(T elem, IMongoQuery query, IMongoUpdate update)
        {
            //var query = Query<Team>.EQ(t => t.Id, elem.Id);
            //var update = Update<Team>.Set(t => t.Name, elem.Name);
            var result = _collection.Update(query, update);
            return (result.Ok && !result.HasLastErrorMessage);
        }

        public bool Delete(T team, IMongoQuery query)
        {
            //var query = Query<T>.EQ(t => t.Id, team.Id);
            var result = _collection.Remove(query);
            return (result.Ok && !result.HasLastErrorMessage);
        }
    }
}
